package cn.android.weblog;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import java.util.Map;

import cn.android.weblog.api.UserAPI;
import cn.android.weblog.domain.User;
import cn.android.weblog.redisdata.CURRENT;
import cn.android.weblog.redisdata.LOGIN;

public class MyInformationActivity extends AppCompatActivity {

    private EditText id,name,sex,email,time,status;
    private ImageView head,back;
    private User user;
    private Button update;
    private UserAPI userAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_information);

        user= LOGIN.USER;
        userAPI=new UserAPI();
        id=(EditText)findViewById(R.id.information_id);
        name=(EditText)findViewById(R.id.information_name);
        sex=(EditText)findViewById(R.id.information_sex);
        email=(EditText)findViewById(R.id.information_email);
        time=(EditText)findViewById(R.id.information_time);
        status=(EditText)findViewById(R.id.information_status);
        update=(Button)findViewById(R.id.information_update);
        head=(ImageView)findViewById(R.id.information_head);
        back=(ImageView)findViewById(R.id.information_back);

        // 初始化页面
        init();

        // 更新个人信息
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUser();
            }
        });

        // 返回上一页
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MyInformationActivity.this,MyActivity.class));
            }
        });

    }

    /**
     * 初始化页面：初始化数据
     */
    private void init(){
        id.setText(user.getUserId().toString());
        name.setText(user.getUsername());
        sex.setText(user.getSex());
        email.setText(user.getEmail());
        time.setText(user.getJoinDate().toString());
        status.setText(user.getStatus()==1?"正常使用":"已注销");
    }

    /**
     * 更新个人信息
     */
    private void updateUser(){
        User u=user;
        u.setUsername(name.getText().toString().trim());
        u.setEmail(email.getText().toString().trim());
        Map<String, Object> map = userAPI.update(u);
        if(map.get("Msg") == null) {
            Toast.makeText(this,"修改成功！",Toast.LENGTH_LONG).show();
            LOGIN.USER= JSON.parseObject(map.get("user").toString(),User.class);
            user=LOGIN.USER;
        }else{
            Toast.makeText(this,map.get("Msg").toString(),Toast.LENGTH_LONG).show();
        }

    }

}
